// Copyright 2006 Mloofle Inc. All Rights Reserved.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;

/**
 * Runs a command-line application to index a corpus.
 */
public class AIM {

  /**
   * Run a command-line application to index a corpus.
   * 
   * @param args the command-line arguments
   */
  public static void main(String[] args) {
    try {
      // Process arguments
      UserSettings settings = ArgumentProcessor.process(args);

      // Create the indexer
      File out = new File("AIM.out");
      RandomAccessFile output = new RandomAccessFile(out, "rw");
      output.setLength(0);
      Indexer indexer = new Indexer(settings, output);

      // Process each input file
      for (int i = 0, c = settings.getFileNameCount(); i < c; ++i) {
        String fileName = settings.getFileName(i);
        InputStream in = null;
        try {
          in = FileStreamCreator.createInputStream(fileName);
          indexer.startNewFile(fileName);
          WordLexer wordLexer = new WordLexer(settings.getCharacterAnalyzer());
          wordLexer.processInput(in, indexer);
        } catch (FileNotFoundException e) {
          System.err.println("Error: input file '" + fileName
              + "' does not exist");
          System.exit(-1);
        } catch (IOException e) {
          System.err.println("Error: input file '" + fileName
              + "' could not be read from");
          System.exit(-1);
        } 
      }

      // Finish the output
      indexer.finish();

      // normal status code 0 exit
      return;
    } catch (IllegalArgumentException e) {
      System.err.println("Error: " + e.getMessage());
    } catch (FileNotFoundException e) {
      System.err.println("Error: could not open output file 'AIM.out'");
    } catch (Indexer.OutputException e) {
      System.err.println("Error: could not write to output file 'AIM.out'");
    } catch (OutOfMemoryError e) {
      System.err.println("Error: out of memory; the corpus may be too large");
    } catch (Throwable e) {
      System.err.println("Error: program terminated unexpectedly");
    }
    // error exit
    System.exit(-1);
  }

  /**
   * Not instantiable.
   */
  private AIM() {
  }

}
